package org.nutz.mvc.view;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.nutz.mvc.View;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * 将数据采用json方式输出的视图，采用FastJson实现
 * 
 * @author bcw(bcw104@126.com)
 */
public class FastJsonView implements View {

    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private SerializerFeature[] serializerFeature;

    private Object data;

    public FastJsonView(SerializerFeature[] serializerFeature) {
        this.serializerFeature = serializerFeature;
    }

    public void setData(Object data) {
        this.data = data;
    }


    public void render(HttpServletRequest req, HttpServletResponse resp, Object obj)
            throws IOException {

        resp.setHeader("Cache-Control", "no-cache");
        //resp.setContentType("text/plain;charset=utf-8");
        resp.setContentType("text/json;charset=utf-8");

        JSON.writeJSONStringTo(obj == null ? data : obj, resp.getWriter(), serializerFeature);
//        String jsonString = JSON.toJSONString(obj == null ? data : obj, serializerFeature);
//        resp.getWriter().write(new String(jsonString.getBytes(DEFAULT_CHARSET)));

        resp.flushBuffer();
    }
}